package com.xbongbong.pro.rabbitmq.consumer;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.message.enums.SmsSendFromTypeEnum;
import com.xbongbong.pro.rabbitmq.binders.SmsConsumerBinder;
import com.xbongbong.pro.rabbitmq.constant.SmsBinderConstant;
import com.xbongbong.pro.rabbitmq.feign.SmsFeignClient;
import com.xbongbong.pro.sms.pojo.dto.SmsRabbitMqDTO;
import com.xbongbong.pro.sms.pojo.vo.SmsRabbitMqVO;
import feign.RetryableException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.handler.annotation.Header;

import javax.annotation.Resource;

/**
 * 短信  消息消费者
 * @author youli.chen
 * @date 2019/3/19 15:32
 * @since v1.0
 * @version v1.0
 */
@EnableBinding(SmsConsumerBinder.class)
public class SmsListener {
    private static Logger logger = LoggerFactory.getLogger(SmsListener.class);

    @Resource
    private SmsFeignClient smsFeignClient;

    /**
     *
     * @param smsMessage 发送短信入参
     * @param sendType 枚举
     */
    @StreamListener(value = SmsBinderConstant.SMS_INPUT)
    public void smsReceive(SmsRabbitMqDTO smsMessage, @Header("sendType") SmsSendFromTypeEnum sendType) {
        XbbResponse<SmsRabbitMqVO> response = null;
        try {
            switch (sendType) {
                case SMS_SEND:
                    response = smsFeignClient.smsSend(smsMessage);
                    break;
                case SMS_SEND_FOR_BUSINESS:
                    response = smsFeignClient.smsSendForBusiness(smsMessage);
                    break;
                case SMS_RE_SEND:
                    response = smsFeignClient.smsReSend(smsMessage);
                    break;
                default:
                    break;
            }
            logger.info("Received: "  + sendType.toString() + "\n message=" + JSON.toJSONString(smsMessage));
        } catch (RetryableException e) {
            logger.error("SmsListener.smsReceive RetryableException case by Read timed out, type=" + sendType);
        } catch (Exception e) {
            logger.error("SmsListener.smsReceive Exception, type=" + sendType, e);
        }
    }
}
